/**
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var prefs_obj;
var searchForm_str = "<form><input size='25' id='searchText' name='searchText' /><input type='submit' id='search_submit' value='Search'/></form>";
var searchURL_tmpl = "http://code.google.com/p/%PROJECT%/w/list?q=%SEARCH%";
var title_tmpl = "%PROJECT% wiki";
var urlMaster_tmpl = 'http://code.google.com/p/%PROJECT%/w/list?sort=%SORT%&colspec=%COLSPEC%&num=10&start=%START%';
var url_tmpl = "";
var projectName_str = "";
var colspec_str = "";

/**
 * Our global to track the current page based on the starting entry
 */
var start_num = 0;

/**
 * Builds the base URL.  As our URL is built partially from UserPrefs, we need this
 * function to be called before our common <code>init()</code>.
 */
function localInit() {
  prefs_obj = new gadgets.Prefs();
  colspec_str = "pagename+changed+changedby";

  // We need the url_tmpl right away for init
  rebuildURL();

  // Call the common init
  init();
}

/**
 * Actually rebuild the URL on paging, colspec, or sort updates.
 */
function rebuildURL() {
  // Construct the url template (it's just missing the project name)
  url_tmpl = urlMaster_tmpl.replace("%SORT%", prefs_obj.getString("sortBy")).replace("%COLSPEC%", colspec_str).replace("%START%", start_num);
}

/**
 * Actually renders the gadget content
 *
 * @param response_str  The retrieved page to scrape.
 */
function render(response_str) {
  // Construct a jQuery object for the results table in our retrieved text
  response_obj = jQuery("#resultstable", jQuery(response_str));

  // Add the search form
  var output_str = searchForm_str;

  // Check for empty return
  if (response_str.search(/This project currently has no wiki pages./) != -1) {
    // Let the user know that there are no items to show
    output_str += "No Wiki pages could be found.";
  } else {
    // Build the data table and paging links
    output_str += buildContent(response_str, response_obj);
  }

  // Inject the HTML
  $("#content_div").html(output_str);

  // Add any paging events
  addPagingEvents(pagingCallback);

  // Add an event handler for the search box that calls a new window at the appropriate search URL
  addSearchEvent();

  // Auto-adjust the gadget height
  adjustIFrameHeight();
}

/**
 * Called by render if there are any items to render.  This function actually renders
 * the HTML data table.
 *
 * @param response_str  The page to scrape.
 * @param respnse_obj   The <code>jQuery</code> object with the <code>#resultstable</code>.
 * @returns             The fully-built result table content string.
 */
function buildContent(response_str, response_obj) {
  var linkCell_tmpl = "<td valign='top' style='border-bottom: 1px solid #BBBBBB;' class='breakword'><a href='http://code.google.com/p/%PROJECT%/wiki/%CONTENT%' target='_blank'>%CONTENT%</a></td>";
  var regularCell_tmpl = "<td valign='top' style='border-bottom: 1px solid #BBBBBB;' class='breakword'>%CONTENT%</td>";

  // Add the data
  var result_str = "";
  result_str += "<center><table cellspacing='0' cellpadding='0' width='100%' id='#resultstable' style='border-top: 1px solid #BBBBBB;'>";

  response_obj.find("tr").each(function(i) {
    result_str += "<tr>";

    jQuery(this).find("td:not(:last):not(:first)").each(function(i) {
      if (jQuery(this).html().search("onclick") == -1) {
        // If this is a title element, add HTML with a link
        result_str += linkCell_tmpl.replace("%PROJECT%", projectName_str)
                                   .replace("%CONTENT%", jQuery(this).text())
                                   .replace("%CONTENT%", ellipsifyWords(jQuery(this).text(), 12));
      } else if (jQuery(this).html().search("vt col_0") != -1) {
        result_str += regularCell_tmpl.replace("%CONTENT%", jQuery(this).text().replace(/\ *ago/, ""));
      } else {
        result_str += regularCell_tmpl.replace("%CONTENT%", jQuery(this).text());
      }
    });
    result_str += "</tr>";
  });
  result_str += "</table></center>";

  // Generate Paging info, add a break even if no paging
  var paging_str = generatePagingFromPage(response_str, start_num);
  result_str += "<br />" + paging_str;

  return result_str;
}

/**
 * Called by paging events, handles paging actions.
 *
 * @param page_num  A page number or <code>PAGE_PREV</code> / <code>PAGE_NEXT</code>
 *                  / <code>PAGE_MORE</code> flag.
 */
function pagingCallback(page_num) {
  if (page_num == PAGE_MORE) {
    // More means we send the user to another page
    moreURL_str = urlMaster_tmpl.replace("%SORT%", prefs_obj.getString("sortBy")) // Set SORT from user pref
                                .replace("&colspec=%COLSPEC%", "")                // Remove COLSPEC - new page will have google defaults
                                .replace("%START%", 40)                           // We'll start at 40.  40 must exist or the more link wouldn't
                                .replace("&num=10", "")                           // Don't limit the listing
                                .replace("%PROJECT%", projectName_str);           // Set the PROJECT from our scratch projectName

    // Open the window
    window.open(moreURL_str, "_blank");
    return;
  }

  if (page_num == PAGE_PREV) {
    start_num -= 10;
  } else if (page_num == PAGE_NEXT) {
    start_num += 10;
  } else {
    start_num = (page_num - 1) * 10;
  }

  // Rebild the URL and call init to get back to our render handler
  rebuildURL();
  init();
}

/**
 * Adds functionality to the search box with and event handler.
 */
function addSearchEvent() {
  $("#search_submit").click(function(event) {
    event.preventDefault();    // Do not let the button do anything else

    // Get the search text
    var searchText_str = $("#searchText").val();
    if (searchText_str != "") {
      // Escape the user's search text
      searchText_str = _esc(searchText_str).replace(/%20/g, "+");

      // Construct the search URL
      var searchURL_str = searchURL_tmpl.replace("%SEARCH%", searchText_str)              // Replace SEARCH with user's search Text
                                        .replace("%PROJECT%", _esc(projectName_str));     // Replace PROJECT with the project name

      // Open the new window (use _blank to always get a new window)
      window.open(searchURL_str, "_blank");
    }
  })
}

gadgets.util.registerOnLoadHandler(localInit);
